package com.ij.media.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ij.media.enums.VideoEnums;
import com.ij.media.mapper.VideoMapper;
import com.ij.media.model.Video;
import com.ij.media.model.VideoVo;
import com.ij.media.service.VideoService;
import com.ij.sso.utils.MyExceptionUtil;
import com.ij.sso.utils.UUIDUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.*;

@Service
public class VideoServiceImpl implements VideoService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    VideoMapper videoMapper;

    @Override
    public int addVideos(List<Video> videos) {
        return videoMapper.insertVideos(videos);
    }

    @Override
    public boolean batchImportExcel(String fileName, MultipartFile file) throws Exception {
        List<Video> videoList = new ArrayList<Video>();
        boolean successState = false;
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new MyExceptionUtil("上传文件格式不正确");
        }
        boolean isExcel2003 = true; // 是否为excel2003
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if (sheet == null) {
            return false;
        }

        //校验每一行
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            Video video = new Video();
            //校验每一列
            for (int i = 0; i <= row.getPhysicalNumberOfCells(); i++) {
                VideoEnums videoEnums = VideoEnums.getVideoEnums(i);
                if (videoEnums == null){
                    continue;
                }

                Cell cell = row.getCell(i);
                String value = null;
                if (cell != null){
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    value = cell.getStringCellValue();
                }
                if (StringUtils.isEmpty(value)){
                    throw new MyExceptionUtil("导入失败（第）"+(r+1)+"行，电影"+ videoEnums.getValue()+"未填写");
                }
                logger.info(value);
                switch (videoEnums) {
                    case NAME: video.setVideoName(value); break;
                    case IMG: video.setVideoImg(value); break;
                    case URL: video.setVideoUrl(value); break;
                    case AREA: video.setVideoArea(value); break;
                    case TIME: video.setVideoLongTime(Integer.parseInt(value)); break;
                    case TYPE: video.setVideoClassily(Integer.parseInt(value)); break;
                    case INTRO: video.setVideoIntro(value); break;

                }
            }
            video.setRandomId(UUIDUtil.getUUID());
            video.setVideoCreatetime(new Date());
            video.setVideoCreateuser("测试1");
            logger.info(video.toString());
            videoList.add(video);
        }
        if (videoList.size()>0){
            logger.info("执行批量插入");
            int size = videoMapper.insertVideos(videoList);
            successState= size>0;
        }
        return successState;
    }

    /**
     * 根据电影条件查询列表信息
     * @param videoVo
     * @return
     */
    @Override
    public Map<String,Object> getVideoListByCondition(VideoVo videoVo) {
        PageHelper.startPage(videoVo.getPageNum(),videoVo.getPageSize());
        List<Video> list = videoMapper.selectByCondition(videoVo);
        PageInfo pageInfo = new PageInfo(list);
        Map<String,Object> result = new HashMap<>();
        result.put("data",pageInfo.getList());
        result.put("total",pageInfo.getTotal());
        return result;
    }

    // 根据randomid删除
    @Override
    public int deleteByRandomId(String randomId) {
        return videoMapper.deleteByRandomId(randomId);
    }
}
